package com.ls.lsbase.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ejl_001 on 2016/11/25.
 */

/**
 * 分享辅助类
 */
public class ShareUtils {
    private static String QQ_APP_ID;
    private static String WX_APP_ID;

    public static void setQqAppId(String qqAppId) {
        QQ_APP_ID = qqAppId;
    }

    public static void setWxAppId(String wxAppId) {
        WX_APP_ID = wxAppId;
    }

    public static void shareToQQ(Activity aty, String TITLE, String DESC, String TURN_URL, String IMG_URL, IUiListener listener) {
        if (null == QQ_APP_ID) {
            Log.e("ls", "you must set this QQ_APP_ID");
            return;
        }
        Tencent mTencent = Tencent.createInstance(QQ_APP_ID, aty.getApplicationContext());
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, TITLE);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, DESC);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, IMG_URL);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, TURN_URL);
        mTencent.shareToQQ(aty, params, listener);
    }

    public static void shareToQzone(Activity aty, String TITLE, String DESC, String TURN_URL, String IMG_URL, IUiListener listener) {
        if (null == QQ_APP_ID) {
            Log.e("ls", "you must set this QQ_APP_ID");
            return;
        }
        Tencent mTencent = Tencent.createInstance(QQ_APP_ID, aty.getApplicationContext());
        Bundle params = new Bundle();
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, TITLE);//必填
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, DESC);//选填
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, TURN_URL);//必填
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());
        mTencent.shareToQzone(aty, params, listener);
    }

    public static void shareToWx(final Context context, final String TITLE, final String DESC, final String TURN_URL, final String IMG_URL, final boolean isTimeline) {
        if (null == WX_APP_ID) {
            Log.e("ls", "you must set this WX_APP_ID");
            return;
        }
        if (isWeixinAvilible(context)) {
            if (null == WX_APP_ID) {
                Log.e("ls", "you must set this WX_APP_ID");
                return;
            }
            final IWXAPI api = WXAPIFactory.createWXAPI(context, WX_APP_ID);
            ImageUtils.getNetBitmap(context, IMG_URL, new ImageUtils.LoadSuccess() {
                @Override
                public void result(Bitmap bitmap) {
                    api.sendReq(ShareUtils.shareToWx(bitmap, TURN_URL, TITLE, DESC, isTimeline));
                }
            });
        } else {
            Toast.makeText(context, "您还没有安装微信，请先安装微信客户端", Toast.LENGTH_SHORT).show();
        }
    }

    private static SendMessageToWX.Req shareToWx(Bitmap bit, String url, String title, String desc, boolean isTimeline) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = desc;
        msg.thumbData = bmpToByteArray(bit,true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
        return req;
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG,  100 , output);
        int options = 100;
        while (output.toByteArray().length / 1024 >= 32) {
            output.reset();
            bmp.compress(Bitmap.CompressFormat.JPEG, options, output);
            options -= 10;
        }
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /*
    * 判断微信是否安装
    * */
    private static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        // 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        // 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
}
